var process = require('child_process');
const mongoose = require('mongoose');
const db_conf = require('./db_conf');
const mongoUrl = db_conf.mongodb;
const startMongoDB = db_conf.dbShell.startMongoDB;

const restartMongoDB = () => {
    process.exec(startMongoDB, (error, stdout, stderr) => {
        if (error !== null) {
          console.log('exec error: ' + error);
          restartMongoDB();
        }
    });
};
try{
    mongoose.connect(mongoUrl, { useNewUrlParser: true });
}catch(error){
    console.log(error);
}

let conn = mongoose.connection;

conn.once('open', () => {
    console.log(new Date().toString() + ' ok! ' + __filename.split('/').pop());
});

conn.on('error', (err) => {
    console.error('数据库连接出错', err);
    restartMongoDB();
});

const Schema = mongoose.Schema;
module.exports = {
    Schema: Schema,
    createModel: (model, attr,textIndexs) => {
        let schema = new Schema(attr, { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } });
        if (textIndexs && textIndexs.length) {
            let obj = {};
            for (let i = 0;i < textIndexs.length; i++){
                obj[textIndexs[i]] = "text";
            }
            schema.index(obj)
        }
        return mongoose.model(model, schema);
    }
};